"""
@-*- coding: utf-8 -*-
@ python: 3.12.3
@ 创建者: JacksonCode
@ 创建时间: 2025-11-06
@ 描述: 认证控制器，处理认证相关的业务逻辑
"""
from flask import request
from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt
from app.common.base_controller import BaseController
from app.services.auth import AuthService
from app.services.users import UserService
from app.utils.validators import validate_email, validate_password
from app.utils.jwt_utils import create_token_response, refresh_token_response, JWTUtils


class AuthController(BaseController):
    """认证控制器，处理认证相关的业务逻辑"""
    
    @staticmethod
    def login():
        """处理用户登录"""
        data = request.get_json()
        
        # 验证请求数据
        if not data or not data.get("email") or not data.get("password"):
            return AuthController.error_response("邮箱和密码不能为空", 400)
        
        # 验证邮箱格式
        if not validate_email(data["email"]):
            return AuthController.error_response("邮箱格式不正确", 400)
        
        # 验证用户凭据
        user = AuthService.authenticate_user(data["email"], data["password"])
        if not user:
            return AuthController.error_response("邮箱或密码错误", 401)
        
        # 更新最后登录时间
        user.update_last_login()
        
        # 使用JWT工具类创建令牌响应
        return AuthController.success_response("登录成功", create_token_response(user, "登录成功"))
    
    @staticmethod
    def register():
        """处理用户注册"""
        data = request.get_json()
        
        # 验证请求数据
        if not data or not data.get("email") or not data.get("password"):
            return AuthController.error_response("邮箱和密码不能为空", 400)
        
        # 验证邮箱格式
        if not validate_email(data["email"]):
            return AuthController.error_response("邮箱格式不正确", 400)
        
        # 验证密码强度
        if not validate_password(data["password"]):
            return AuthController.error_response("密码必须至少8位，包含字母和数字", 400)
        
        # 创建用户
        user, error = AuthService.create_user(
            email=data["email"],
            password=data["password"],
            username=data.get("username")
        )
        
        if error:
            return AuthController.error_response(error, 400)
        
        user_data = {
            "id": user.id,
            "email": user.email,
            "username": user.username
        }
        
        return AuthController.success_response("注册成功", {"user": user_data}, 201)
    
    @staticmethod
    @jwt_required()
    def get_current_user():
        """获取当前用户信息"""
        user_id = get_jwt_identity()
        user = AuthService.get_user_by_id(user_id)
        
        if not user:
            return AuthController.not_found_response("用户")
        
        user_data = {
            "id": user.id,
            "email": user.email,
            "username": user.username,
            "is_admin": user.is_admin,
            "created_at": user.created_at.isoformat() if user.created_at else None
        }
        
        return AuthController.success_response("获取用户信息成功", {"user": user_data})
    
    @staticmethod
    @jwt_required()
    def update_profile():
        """更新用户资料"""
        user_id = get_jwt_identity()
        data = request.get_json()
        
        if not data:
            return AuthController.error_response("请提供更新数据", 400)
        
        # 更新用户资料
        user, error = UserService.update_user_profile(user_id, data)
        
        if error:
            return AuthController.error_response(error, 400)
        
        user_data = {
            "id": user.id,
            "email": user.email,
            "username": user.username
        }
        
        return AuthController.success_response("更新成功", {"user": user_data})
    
    @staticmethod
    @jwt_required(refresh=True)
    def refresh():
        """刷新访问令牌"""
        return AuthController.success_response("令牌刷新成功", refresh_token_response())
    
    @staticmethod
    @jwt_required()
    def logout():
        """处理用户登出"""
        JWTUtils.revoke_token()
        return AuthController.success_response("登出成功")